#!/usr/bin/env python3
"""
PHP MCP Server

面向 php 软件的 MCP Server，提供 php-fpm 服务管理和配置操作的工具。

MCP tools 列表：
- php_fpm_service_control: 控制 php-fpm 服务的启动、重载和状态检查
  参数：action (str) - 服务操作类型：start/reload/status
  返回：统一的 JSON 结构

- php_fpm_config_modify: 修改 php-fpm 服务的配置文件
  参数：file_path (str) - 配置文件路径
        search_pattern (str) - 要搜索的模式
        replace_pattern (str) - 要替换的模式
  返回：统一的 JSON 结构
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("PHP MCP Server")

@mcp.tool()
def php_fpm_service_control(action: str) -> Dict[str, Any]:
    """
    控制 php-fpm 服务的启动、重载和状态检查
    
    参数:
        action: 服务操作类型，支持 'start'（启动）、'reload'（重载）、'status'（状态检查）
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ['start', 'reload', 'status']
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} php-fpm.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = f"systemctl {action} php-fpm.service"
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def php_fpm_config_modify(file_path: str, search_pattern: str, replace_pattern: str) -> Dict[str, Any]:
    """
    使用 sed 命令修改 php-fpm 服务的配置文件
    
    参数:
        file_path: 要修改的配置文件路径
        search_pattern: 要搜索的文本模式
        replace_pattern: 要替换的文本模式
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 操作是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    # 转义 sed 模式中的特殊字符
    escaped_search = search_pattern.replace('/', '\\/')
    escaped_replace = replace_pattern.replace('/', '\\/')
    
    command = f"sed -i 's/{escaped_search}/{escaped_replace}/g' {file_path}"
    
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()